package com.goodomen.garbage.web.service.system;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goodomen.garbage.common.persistence.mapper.system.SysRoleMapper;
import com.goodomen.garbage.common.persistence.model.system.SysRole;
import com.goodomen.garbage.web.dto.SysRoleDto;
import com.goodomen.garbage.web.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 系统用户角色 Service
 *
 * @author : zhaoda
 * @since 2019/7/29 13:31
 */
@Service
@Slf4j
public class SysRoleService {

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 根据角色ID 查找角色信息
     * @param id    角色ID
     * @return
     */
    public SysRole findById(Long id) {
        return sysRoleMapper.selectByPrimaryKey(id);
    }


    /**
     * 分页查询权限列表
     *
     * @param pageNum    页码
     * @param pageSize   分页大小
     * @param sysRoleDto 查询条件
     * @return PageInfo<SysRole>
     */
    public PageInfo<SysRole> selectList(int pageNum, int pageSize, SysRoleDto sysRoleDto) {
        pageNum = pageNum > 100 ? 100 : pageNum;
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(sysRoleDto, sysRole);
        return PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> {
            sysRoleMapper.selectList(sysRole);
        });
    }

    /**
     * 更新系统权限
     * @param sysRole   系统权限
     * @return
     */
    public Integer update(SysRole sysRole) {
        try {
            return sysRoleMapper.updateByPrimaryKeySelective(sysRole);
        } catch (SqlSessionException e) {
            log.error("角色信息更新异常 SysRoleService.update()", e);
        }
        return 0;
    }

    public SysRole findPermissionByRoleId (Long roleId) {
        return sysRoleMapper.selectByPrimaryKey(roleId);
    }

    public Integer insert(SysRole sysRole) {
        try {
            return sysRoleMapper.insertSelective(sysRole);
        } catch (SqlSessionException e) {
            log.error("角色信息新增异常 SysRoleService.update()", e);
        }
        return 0;
    }

    public Integer delete(Long id) {
        try {
            return sysRoleMapper.deleteByPrimaryKey(id);
        } catch (Exception e) {
            log.error("角色信息删除异常 SysRoleService.delete()", e);
        }
        return 0;
    }
}
